<?php
namespace app\common\model;

class Comment extends BaseModel{
	protected $insert = ['ip', 'reply_user_id'];
	/**
	 * 模块修改器
	 * @param string $module 模块内容
	 * @param [type] $data   提交数据
	 */
	public function setModuleAttr($module = '', $data){
		$module    = $module ? $module : $data['module'];
		$object_id = $data['object_id'];

		if(!$data['comment_id']){
			switch ($module) {
				case 'ask':
					db('Ask')->where(['ask_id' => $object_id])->setInc('comment_num');
					break;

				case 'ask_answer':
					db('AskAnswer')->where(['answer_id' => $object_id])->setInc('comment_num');
					break;
				
				default:
					# code...
					break;
			}
		}
		return $module;
	}
	/**
	 * 回复用户ID修改器
	 * @param integer $reply_user_id 回复用户ID
	 * @param array   $data          数据
	 */
	public function setReplyUserIdAttr($reply_user_id = 0, $data = []){
		$reply_id = $data['reply_id'];
		if(!$reply_user_id && $reply_id){
			$reply_user_id = $this->where(array('comment_id' => $reply_id))->value('user_id');
		}

		return $reply_user_id ? $reply_user_id : 0;
	}
	/**
	 * 获取回复用户名称
	 * @param  string $reply_user_id 回复用户ID
	 * @param  array  $data          数据
	 */
	public function getReplyUserNameAttr($reply_user_id = '', $data = []){
		$reply_user_id = $reply_user_id ? $reply_user_id : $data['reply_user_id'];
		$user_name     = $this->getUserNameAttr($reply_user_id);

		return $user_name ? $user_name : '';
	}
	/**
	 * 标题获取器
	 * @param  integer $object_id 对象ID
	 * @param  array   $data      数据记录
	 */
	public function getTitleAttr($object_id = 0, $data= []){
		$object_id = $object_id ? $object_id : $data['object_id'];
		$module    = $data['module'];

		$title = '';
		switch ($module) {
			case 'ask':
				$title = db('Ask')->where(['ask_id' => $object_id])->value('title');
				break;

			case 'ask_answer':
				$ask_id = db('AskAnswer')->where(['answer_id' => $object_id])->value('ask_id');
				$title  = db('Ask')->where(['ask_id' => $ask_id])->value('title');
				break;
			
			default:
				break;
		}

		return $title ? $title : '';
	}
	/**
	 * 更新评价数量
	 * @param  [type] $object_id 评价对象ID
	 * @param  [type] $module    模块
	 */
	public function updateCommentNum($object_id, $module){
		if(!$object_id || !$module){
			return false;
		}
		$comment_num = 0;
		switch ($module) {
			case 'ask':
				db('Ask')->where(['ask_id' => $object_id])->setDec('comment_num');
				$comment_num = db('Ask')->where(['ask_id' => $object_id])->value('comment_num');
				break;

			case 'ask_answer':
				db('AskAnswer')->where(['answer_id' => $object_id])->setDec('comment_num');
				$comment_num = db('AskAnswer')->where(['answer_id' => $object_id])->value('comment_num');
				break;
			
			default:
				# code...
				break;
		}

		return $comment_num;
	}
}